package at.chl.lution.creator;

import java.util.List;

import at.chl.genetic.function.math.random.MathRandomUtil;
import at.chl.genetic.function.math.random.RandomMathDecisionNodeFactory;
import at.chl.genetic.node.IDecisionNode;
import at.chl.genetic.random.IRandomDecisionNodeFactory;
import at.chl.genetic.util.NodeUtil;

public class MathGenerationCreator implements IGenerationCreator {

	@Override
	public IDecisionNode createNewGeneration(IDecisionNode parentNode,IRandomDecisionNodeFactory nodeFactory) {
		
		//clone nodetree from parent and save all node from thos tree in list, which will be used as ancorpool
		List<IDecisionNode> ancorPool=NodeUtil.getRootHeadedClonedDecisionTreeEntries(parentNode);
		
		
		
		long ancorSize=ancorPool.size();
		
		//if there is just one ancor, its the root and it has no childs, create a completly new child
		if(ancorPool.size()==1){
			return nodeFactory.createDecisionTree();
		}
		//otherwise get a random index for the ancorpool
		long randomAncorIndex=MathRandomUtil.getRandomLong(ancorSize);
		
		
		//get the random ancor
		IDecisionNode ancor=ancorPool.get((int)(randomAncorIndex));
		
		//get a random child from the ancor
		long ancorChildSize=ancor.getChildNodes().size();
		long randomAncorChildIndex=MathRandomUtil.getRandomLong(ancorChildSize);
		
		//because root is the first element of the list just take this as clonedroot
		IDecisionNode clonedRoot=ancorPool.get(0);
		
		//add a new tree instate of the child
		ancor.getChildNodes().set((int)randomAncorChildIndex, nodeFactory.createDecisionTree(NodeUtil.getNodeDepth(ancor,clonedRoot),(long)ancorPool.size()));
		
		
		return clonedRoot;
	}

}
